package com.itheima.security;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import com.itheima.pojo.SysUser;
import com.itheima.service.UserService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.ArrayList;
import java.util.List;

public class SecurityConfigUserService implements UserDetailsService {

    @Reference
    UserService userService;

    /**
     *  1.通过用户名查询用户信息
     *  2.封装UserDetails返回
     *
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser sysUser = userService.findByUsername(username);

        if (sysUser != null){
            //创建权限集合
            List<GrantedAuthority> authorityList = new ArrayList<>();

            //遍历角色
            for (Role role : sysUser.getRoles()) {
                //遍历权限
                for (Permission permission : role.getPermissions()) {

                    //把权限加入到权限集合中
                    SimpleGrantedAuthority grantedAuthority = new SimpleGrantedAuthority(permission.getKeyword());
                    authorityList.add(grantedAuthority);

                }
            }

            //2.封装UserDetails返回
            UserDetails userDetails = new User(sysUser.getUsername(),sysUser.getPassword(),authorityList);

            return userDetails;
        }
        return null;

    }

}

